//index.js
//获取应用实例
import * as echarts from '../../ec-canvas/echarts';
const common = require('../../utils/common.js');

const app = getApp();

const ctx = wx.createCanvasContext("bgCanvas"); //创建一个全局的canvas绘图上下文
const ctx2 = wx.createCanvasContext("runCanvas");
let mytime = "";
let n = 0;
var w = "";
var h = "";
var echartCanvase, signEchartCanvas;

Page({
  data: {
    showDialogForGetUserInfo:false,
    tempData:{
      hasUserInfo: 1,
      hasWeChatRun:1,
      hasToken: true,
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      isUserIn:true,
    },
    motto: 'Hello World',
    userInfo: {},
    topDepartmentMes:{},  //顶级部门的信息
    topDepartmentStatisticsObj: {},  //顶级部门统计的信息
    yxrdbl:0,
    dbrjbs:0,
    departTodaysRank:[],//部门排行

    //顶部选项卡
    navbar: ['个人排行', '单位排行'],
    currentTab: 0,

    //个人排行选项卡
    ranking: [{
      name: '今日排名',
      icon: '/images/rank.png'
    },{
      name: '本周排名',
      icon: '/images/rank.png'
    }, {
      name: '本月排名',
      icon: '/images/rank.png'
    }],
    rankcurrentTab: 0,
    iconrankcurrentTab: 0,
    myRankingNum:0,

    //部门排行选项卡
    departRanking: [{
      name: '今日排名'
    }, {
      name: '本周排名'
    }, {
      name: '本月排名'
    }],
    departRankcurrentTab: 0,

    star: "",
    level: "",
    allHistoryStep: "",


    //封面内容
    departmentId: "",
    departmentName: '宁波教育工会',
    departId: "",
    departName: "",    // 所属部门名字
    stepNum: 0,    // 顶层工会均步
    peopleNum: 0,
    effectiveDateNum:0,
    departStepNum: 0,    // 个人所属部门均步
    departRank: 0,    // 在所属部分的用户排名

    //签到
    is_say_yes: false,

    //计步器
    score: 0,  //传入的进度， 0~100，绘制到此参数处停止。
    ineffectiveDate: '/images/yes_no.png',
    effectiveDate: '/images/yes_yes.png',

    //个人步数排行榜
    //今日步数
    todaysRank: [],
    //部门平均步数排行榜
    //今日排名
    departTodaysRank: [],
    //本周排名
    departWeeksRank: [],
    //本月排名
    departMonthsRank: [],

    //部门排名中的数据分析
    //饼图
    pieec: {},
    signpieec: {},
    totalNum: '400',
    effectiveNum: '340',
    effectiveRate: '85',
    standardAvePeoStep: '12453',
    signInNum: 0,
    signInRate: '96',


    ifSCode: 0,
    sCodeTrue: 1
  },
  //选项卡
  navbarTap: function (e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
  },
  rankingTap: function (e) {
    this.setData({
      rankcurrentTab: e.currentTarget.dataset.idx,
      iconrankcurrentTab: e.currentTarget.dataset.idx
    })
  },
  departRankingTap: function (e) {
    this.setData({
      departRankcurrentTab: e.currentTarget.dataset.idx,
      ifSelect: true
    })
  },
  siginTap: function (e) {
    let _this = this;
    if (!_this.data.is_say_yes){
      wx.showLoading({
        title: '正在签到',
      });
      wx.request({
        url: app.getUrl().putSignUrl,
        method: "POST",
        data: { token: app.data.token },
        success(_data) {
          console.log(_data);
          _this.setData({
            is_say_yes: true,
            signInNum: _this.data.signInNum+1
          })
        },
        complete(){
          wx.hideLoading();
        }
      })
    }
  },
  //事件处理函数
  // bindViewTap: function () {
  //   wx.navigateTo({
  //     url: '../logs/logs'
  //   })
  // },
  run(e) {
    let that = this;
    let src = that.data.src; //每个间隔所需绘制的弧度
    let allSrc = that.data.allSrc; //总共需要绘制的弧度
    n++;
    let grade = src * (n+1) > allSrc?that.data.score:Math.round(src * n / 1.5 * 20000); //百分数
    
    ctx2.arc(w, h, w - 8, 0.75 * Math.PI, (0.75 + src * n) > 2.25 ? 2.25 * Math.PI : (0.75 + src * n) * Math.PI); //每个间隔绘制的弧度
    ctx2.setStrokeStyle("#52A9FF"); //进度线条颜色
    ctx2.setLineWidth("8");
    ctx2.setLineCap("round");
    ctx2.stroke();
    ctx2.beginPath();
    ctx2.setFontSize(40); //注意不要加引号
    ctx2.setFillStyle("#52A9FF"); //步数颜色
    ctx2.setTextAlign("center");
    ctx2.setTextBaseline("middle");
    ctx2.fillText(grade, w, h);

    ctx2.setFontSize(20); //注意不要加引号
    ctx2.setFillStyle("#52A9FF"); //名次颜色
    ctx2.setTextAlign("center");
    ctx2.setTextBaseline("middle");
    ctx2.fillText('第' + that.data.myRankingNum+"名", w, h - 50);

    ctx2.draw();

    if (src == 0 || allSrc == 0 || src * n > allSrc) {
      //clearInterval(mytime); //如果绘制完成，停掉计时器，绘制结束
      n = 0;
      return;
    } else {
      setTimeout(function () {
        that.run(e)
      }, 1);
    }
  },
  echartInit(e) {
    console.log(e);
    echartCanvase = e;
    
  },
  signechartInit(e) {
    signEchartCanvas = e;
    console.log(e);
  },
  canvasTap() {
    let that = this;
    clearInterval(mytime);
    let allSrc = 0.000075 * that.data.score ; //应该绘制的弧度
    console.log("所有的弧度："+allSrc);
    //计算出每个间隔应该绘制多少弧度。 
    let src = allSrc / 40 
    that.setData({
      src: src,
      allSrc: allSrc
    })
    //mytime = setInterval(that.run, 1) //5毫秒移动一单位
    that.run();
  },
  toTermActivity: function() {
    wx.navigateTo({
      url: '/pages/termActivity/termActivity'
    })
  },
  toYearActivity: function() {
    wx.navigateTo({
      url: '/pages/glorious/glorious'
    }) 
  },
  onLoad: function (options) {
    let _this = this;
    console.log(options);
    _this.setData({
      ifSCode: options.fromtype
    });
  },
  toDetail: function (e) {
    wx.navigateTo({
      url: '/pages/personalDetail/personalDetail?phone=' + this.data.userInfo.guildUser.user_mobile,
    })
  },
  toDepartDetailLg: function (e) {
    wx.navigateTo({
      url: '/pages/departmentCenter/departmentCenter?id=1&num=1'
    });
  },
  toDepartDetailSm: function (e) {
    console.log(this.data.departId);
    wx.navigateTo({
      url: '/pages/departmentCenter/departmentCenter?id=' + this.data.departId + '&num=1'
      })
  },
  // 个人点击时间
  personClick(_e){
    wx.navigateTo({
      url:"/pages/personalDetail/personalDetail?phone="+_e.currentTarget.dataset.phone,
      success(){

      }
    });
  },
  // 获取今日用户数据
  getTodayInfo(){
    console.log(this.data.userInfo);
    console.log(JSON.parse(this.data.userInfo.guildUser.user_department));
    var userdepart = JSON.parse(this.data.userInfo.guildUser.user_department)[0];
    var userMobile = this.data.userInfo.guildUser.user_mobile;

    let _this = this;
    wx.request({
      url: app.getUrl().getIndexInfoUrl,
      method:"post",
      data: { token: app.data.token, department_id: userdepart},
      success(_data){
        console.log(_data);
        console.log(_data.data.info.department_step_sum[0].step_number);

        switch (_data.data.message){
          case "OK":
          case "ok":
            let step = parseInt(_data.data.info.department_step_num.length > 0 && _data.data.info.department_step_num[0].step_number? _data.data.info.department_step_num[0].step_number:0);
            let departStep = parseInt(_data.data.info.department_step_sum.length > 0 && _data.data.info.department_step_sum[0].step_number ? _data.data.info.department_step_sum[0].step_number : 0);

            var userRank = _data.data.info.department_step;
            var specificRank = "";
            userRank.forEach(function(item, index) {
              if (userMobile == item.user_mobile) {
                specificRank = item.rank;
              }
            })

            _this.setData({
              score: _data.data.info.my_step ? _data.data.info.my_step.step_number:0,
              myRankingNum: _data.data.info.my_step ? _data.data.info.my_step.rank:0,
              stepNum: _data.data.info.effective_department_num?Math.ceil(step / _data.data.info.effective_department_num):0,
              departStepNum: _data.data.info.department_sum ? Math.ceil(departStep/_data.data.info.department_sum):0,
              peopleNum: _data.data.info.department_num,
              effectiveDateNum: _data.data.info.department_effective_day_num,
              signInNum: _data.data.info.sign_num,
              is_say_yes: _data.data.info.sign==0?false:true,
              departmentId: _data.data.info.department_info.department_id,
              departId: _data.data.info.department_info.department_id,
              departName: _data.data.info.department_info.department_name,
              departRank: specificRank,
              level: _data.data.info.level.level_name,
              star: _data.data.info.level.level_stars,
              allHistoryStep: _data.data.info.sum_step_number

            });
            _this.canvasTap();

          break;
          default:
            wx.showToast({
              title: "今日数据返回错误，请稍后再试！",
              icon: "none",
              duration: 3000
            });
          break;
        }
      }
    })
  },
  // 获取今日个人排行榜
  getUserRankList(_startDate,_endDate,_callBackFun){
    let _this = this;
    let startTimeObj = common.getTimeFromDay(_startDate ?_startDate:new Date());
    let endTimeObj = common.getTimeFromDay(_endDate ? _endDate : new Date());
    wx.showLoading({
      title: '正在加载',
      mask:true
    })
    wx.request({
      url: app.getUrl().getUserRankLiatUrl,
      method:"POST",
      data: { token: app.data.token, start: Math.floor(startTimeObj.startTime / 1000), end: Math.floor(endTimeObj.endTime/1000)},
      success(_data){
        switch (_data.data.message){
          case "OK":
          case "ok":
            if (typeof _callBackFun == "function"){
              _callBackFun(_data.data.info);
            }else{
              // console.log(app.formatName(_data.data.info[2].user_name));
              _this.setData({
                todaysRank: _data.data.info
              });
            }
          break;
        }
      },
      complete(){
        wx.hideLoading();
      }
    })
  },
  // 初始化完成后每个页面会执行的函数
  initPageData() {
    let _this = this;
    // 获取今日用户数据
    _this.getTodayInfo();
    _this.getUserRankList();  //今日数据
    _this.getUserRankList(new Date(new Date().getTime() - 6*24*60*60*1000),new Date(),function(_list){
      _this.setData({
        weeksRank: _list,
      })
    });  //本周数据
    _this.getUserRankList(new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000), new Date(), function (_list) {
      _this.setData({
        monthsRank: _list
      })
    });  //本月数据
    app.getDepartmentInfo(1,function(_data){
      console.log(_data);
      _this.setData({
        topDepartmentMes: _data
      });
    });

// 获取主体部门统计数据
    // app.getDepartmentStatistics(1,new Date(),new Date(),function(_data){
    //   console.log(_data);
    //   _this.setData({
    //     topDepartmentStatisticsObj: _data,
    //     yxrdbl: Math.ceil(_data.department_effective_day_num / _data.department_num *100),
    //     dbrjbs: _data.sign_num>0? Math.ceil(_data.department_effective_step_num[0].step_number / _data.sign_num):0,
    //     qdl: Math.ceil(_data.sign_num / _data.department_num*100)
    //   });
    //   _this.initPieChart(echartCanvase.detail.canvas, echartCanvase.detail.width, echartCanvase.detail.height);
    //   _this.initSignPieChart(signEchartCanvas.detail.canvas, signEchartCanvas.detail.width, signEchartCanvas.detail.height);
    // });

// 获取部门今日排行
    _this.getDepartmentRankList();

    // 获取部门本周排行
    _this.getDepartmentRankList(new Date(new Date().getTime() - 6 * 24 * 60 * 60 * 1000), new Date(),7,function (_list) {
      _this.setData({
        departWeeksRank: _list,
      });
    });

    // 获取部门本月排行
    _this.getDepartmentRankList(new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000), new Date(), 31,function (_list) {
      _this.setData({
        departMonthsRank: _list
      })
    });
  },
  // 饼图
  initPieChart(canvas, width, height) {
    let _this = this;
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height
    });
    canvas.setChart(chart);

    var option = {
      backgroundColor: 'transparent',
      backgroundColor: "#ffffff",
      color: ["#FC8D52", "#48CFAE"],
      tooltip: {
        show: true,
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        left: '35',
        orient: 'vertica',
        textStyle: {
          fontSize: 16
        }
      },
      series: [{
        label: {
          normal: {
            position: 'inner',
            textStyle: {
              fontWeight: 300,
              fontSize: 16    //文字的字体大小
            },
            formatter: '{d}%'
          }
        },
        type: 'pie',
        center: ['100', '110'],
        radius: [0, '60'],
        data: [{
          value: _this.data.topDepartmentStatisticsObj.department_num - _this.data.topDepartmentStatisticsObj.department_effective_day_num,
          name: '未达标人数'
        }, {
          value: _this.data.topDepartmentStatisticsObj.department_effective_day_num,
          name: '达标人数'
        }],

        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 2, 2, 0.3)'
          }
        }
      }]
    };

    chart.setOption(option);
    return chart;
  },
// 获取今日部门排名
  getDepartmentRankList(_startDate, _endDate,_day, _callBackFun){
    let _this = this;
    wx.request({
      url: app.getUrl().getDepartmentRankListUrl,
      method:"GET",
      data: { token: app.data.token, start: _startDate ? Math.floor(common.getTimeFromDay(_startDate).startTime / 1000) : Math.floor(common.getTimeFromDay(new Date()).startTime / 1000), end: _endDate ? Math.floor(common.getTimeFromDay(_endDate).endTime / 1000) : Math.floor(common.getTimeFromDay(new Date()).endTime / 1000) , day: _day ?_day:1},
      success(_data){
        console.log(_data);
        switch (_data.data.message){
          case "OK":
          case "ok":
            if (typeof _callBackFun == "function") {
              _callBackFun(_data.data.info.department_avg_step_list);
            } else {
              _this.setData({
                departTodaysRank: _data.data.info.department_avg_step_list
              });
            }
          break;
        }

      },
    })
  },

  initSignPieChart(canvas, width, height) {
    let _this = this;
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height
    });
    canvas.setChart(chart);

    var option = {
      backgroundColor: 'transparent',
      color: ["#EC87BF", "#FFCE55"],
      tooltip: {
        show: true,
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        left: '35',
        orient: 'vertica',
        textStyle: {
          fontSize: 16
        }
      },
      series: [{
        label: {
          normal: {
            position: 'inner',
            textStyle: {
              fontWeight: 300,
              fontSize: 16    //文字的字体大小
            },
            formatter: '{d}%'
          }
        },
        type: 'pie',
        center: ['260', '100'],
        radius: [0, '60'],
        data: [{
          value: _this.data.topDepartmentStatisticsObj.department_num-_this.data.topDepartmentStatisticsObj.sign_num,
          name: '未签到'
        }, {
          value: _this.data.topDepartmentStatisticsObj.sign_num,
          name: '已签到'
        }],

        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 2, 2, 0.3)'
          }
        }
      }]
    };

    chart.setOption(option);
    return chart;
  },

  clickToDepartment(_event){
    console.log(_event);
    wx.navigateTo({
      url: '/pages/departmentCenter/departmentCenter?id=' + _event.currentTarget.dataset.id,
    })
  },
   /**
   * 生命周期函数--页面显示/切入前台时触发。
   */
  onShow:function(option){
    let _this = this;
    app.commonOnLoad(this);
    
    var obj = wx.getLaunchOptionsSync();
    console.log(obj.scene);
    if (obj.scene == 1011 || obj.scene == 1012 || obj.scene == 1013 || obj.scene == 1025 || obj.scene == 1047 || obj.scene == 1048 || obj.scene == 1049 || obj.scene == 1031 || obj.scene == 1032 || obj.scene == 1037 || sCodeTrue == ifSCode) {
      wx.request({
        url: app.getUrl().putSignUrl,
        method: "POST",
        data: { token: app.data.token },
        success(_data) {
          console.log(_data);
          _this.setData({
            is_say_yes: true,
            signInNum: _this.data.signInNum + 1
          })
        },
        complete() {
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   

    wx.createSelectorQuery().select('#canvas-one').boundingClientRect(function (rect) {//监听canvas的宽高
      console.log(rect);
      w = parseInt(rect.width / 2);
      //获取canvas宽的的一半
      h = parseInt(rect.height / 2);
      //获取canvas高的一半，
      //获取宽高的一半是为了便于找到中心点

      ctx.arc(w, h, w - 8, 0.75 * Math.PI, 2.25 * Math.PI); //绘制圆形弧线
      ctx.setStrokeStyle("#dddddd"); //设置填充线条颜色
      ctx.setLineWidth("8");     //设置线条宽度
      ctx.setLineCap("round");        //设置线条端点样式
      ctx.stroke();     //对路径进行描边，也就是绘制线条

      ctx.draw();       //开始绘制
    }).exec()

    

  }
})